package com.chinalin.h5_webrtc_host

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.inputmethod.EditorInfo
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isInvisible
import androidx.lifecycle.MutableLiveData
import com.chinalin.h5_webrtc_host.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "MainActivity"
        fun start(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
        }
    }

    private var _binding: ActivityMainBinding? = null
    private val binding get() = _binding!!
    // private val currentUrl = MutableLiveData("https://webrtc.github.io/samples/src/content/getusermedia/gum/")
    // private val currentUrl = MutableLiveData("https://appkhtest.chinalin.com:8081/hlzq-stkkh-hvue/views/index.html#/index")
    private val currentUrl = MutableLiveData("https://webrtc.github.io/samples/src/content/devices/input-output/")

    private val currentProgress = MutableLiveData(0)

    // Activity 需要持有这个回调，因为 WebChromeClient 的生命周期与 WebView 绑定
    private var fileUploadCallback: ValueCallback<Array<Uri>>? = null

    // 处理文件选择器的返回结果
    private val fileChooserLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            val uris = WebChromeClient.FileChooserParams.parseResult(result.resultCode, result.data)
            fileUploadCallback?.onReceiveValue(uris)
            fileUploadCallback = null
        }

    private fun updateUrl(url: String){
        binding.etLink.setText(url)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LastUrlUtils.getUrl().takeIf { it.isNotEmpty() }?.let { currentUrl.value = it }
        val li = LayoutInflater.from(this)
        _binding = ActivityMainBinding.inflate(li)
        setContentView(binding.root)
        updateUrl(currentUrl.value.orEmpty())
        binding.etLink.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.tvGo.performClick()
                true
            } else {
                false
            }
        }

        // ✨ 一键调用，完成所有配置！ ✨
        WebViewUtils.setupSuperWebView(
            webView = binding.wvWeb,
            activity = this,
            fileChooserLauncher = fileChooserLauncher,
            onFileUploadCallbackSet = { callback ->
                this.fileUploadCallback = callback
            },
            onProgress = {
                this.currentProgress.value = it
            },
            onUrlChanged = {
                updateUrl(it)
            }
        )

        binding.wvWeb.apply {
            binding.tvGo.setOnClickListener {
                val dst = binding.etLink.text.toString()
                currentUrl.postValue(dst)
            }
            binding.tvNext.setOnClickListener {
                if (canGoForward()) {
                    goForward()
                }
            }
            binding.tvPrev.setOnClickListener {
                if (canGoBack()) {
                    goBack()
                }
            }
        }

        currentUrl.observe(this) {
            val dst = currentUrl.value.orEmpty()
            LastUrlUtils.setUrl(dst)
            binding.wvWeb.loadUrl(dst)
        }

        currentProgress.observe(this) {
            val dst = currentProgress.value ?: 0
            Log.i(TAG, "progress $it")

            binding.pbProgress.setProgress(dst, false)
            binding.pbProgress.isInvisible = (it in 1..99).not()
        }
    }

    override fun onBackPressed() {
        if (binding.wvWeb.canGoBack()) {
            binding.wvWeb.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        binding.wvWeb.destroy()
        super.onDestroy()
    }
}